package org.jetnuke.common;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

public class PropertiesManager {
	//private static PropertiesManager instance;

	private PropertiesManager() {
	}

	public static int time = 1;
//	static {
//		//instance = new PropertiesManager();
//	}

	static Hashtable propertiesCache = new Hashtable(100);

	public static Properties getProperties(String resourcePath, long now) {
		PropertiesResource resource = (PropertiesResource) propertiesCache
				.get(resourcePath);

		if (resource != null) {
			/*
			 * refresh the resource
			 */

			try {
				refreshResource(resource, now);
			} catch (Exception rnfe) {
				/*
				 * something exceptional happened to that resource this could be
				 * on purpose, so clear the cache and try again
				 */

				propertiesCache.remove(resource);

				return getProperties(resourcePath, now);
			}

		} else {
			resource = loadResource(resourcePath, now);
			propertiesCache.put(resourcePath, resource);
		}
		if (resource != null)
			return resource.getProperties();
		else
			return new Properties();
	}

	/**
	 * @return
	 */
	private static PropertiesResource loadResource(String path, long now) {

		Properties pp = loadProperties(path);
		PropertiesResource pr = new PropertiesResource();
		pr.setProperties(pp);
		pr.setPath(path);
		pr.lastModified = now;
		return pr;
	}

	/**
	 * @param resource
	 */
	private static void refreshResource(PropertiesResource resource, long now) {

		synchronized (resource) {
			if (resource.lastModified < now - 1000 * time) {//TODO
				resource.setProperties(loadProperties(resource.getPath()));
				resource.lastModified = now;
			}
		}

	}

	private static Properties loadProperties(String path) {
		Properties pp = new Properties();
		try {
			//URL url = instance.getClass().getClassLoader().getResource(path);
			//if (url != null) {
				InputStream is = new BufferedInputStream(new FileInputStream(path));
				pp.load(is);
				is.close();
			//}
		} catch (Throwable e) {
			
		}
		return pp;
	}

	/**
	 * @return Returns the time.
	 */
	public static int getTime() {
		return time;
	}

	/**
	 * @param time
	 *            The time to set.
	 */
	public static void setTime(int time) {
		PropertiesManager.time = time;
	}
}
